package com.kc.gb.device.plugins.ptl.starter;

import com.kc.gb.base.dto.DeviceType;
import com.kc.gb.base.dto.Result;
import com.kc.gb.device.common.dto.RefreshUIEvent;
import com.kc.gb.device.common.interfaces.IHardware;
import com.kc.gb.device.common.properties.DeviceProperties;
import com.kc.gb.device.common.utils.SpringHelper;
import com.kc.gb.device.plugins.ptl.service.PtlMQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author : GlobalApplicationRunner
 * @version V1.0
 * @date: 2023/11/29 10:55 AM
 * @Description: TODO
 */
@Slf4j
@Component
public class PtlApplicationRunner implements ApplicationRunner {

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    PtlMQService ptlMQService;

    @Resource
    DeviceProperties deviceProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        IHardware hardware = (IHardware) SpringHelper.getApplicationContext().getBean(DeviceType.PTL.name());
        if(!hardware.isEnabled()){
            log.info("DevicePtlEnabled:{}",false);
            return;
        }
        threadPoolTaskExecutor.execute(()->{
            Result<?> result = null;
            try {
                result = hardware.initialize();
            } catch (Throwable e) {
                log.error("PTLHardware:{}",e.getMessage(),e);
                result = Result.fail(e.getClass().getSimpleName());
            }
            // 保存初始化的结果
            try {
                hardware.afterInitialize(result);
                SpringHelper.getApplicationContext().publishEvent(new RefreshUIEvent(DeviceType.PTL));
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        });
        threadPoolTaskExecutor.execute(()->{
            try {
                ptlMQService.createCommandProducer();
            } catch (Exception e) {
                log.error("MQService create producer:{}",e.getMessage(),e);
            }
            try {
                ptlMQService.createCommandConsumer();
            } catch (Exception e) {
                log.error("MQService create consumer:{}",e.getMessage(),e);
            }
        });
    }
}
